<!DOCTYPE html>
<html>

<head>
    <!-- 页面meta -->
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>商品编辑</title>
    <!-- Tell the browser to be responsive to screen width -->
    <meta content="width=device-width,initial-scale=1,maximum-scale=1,user-scalable=no" name="viewport">
  
    <link rel="stylesheet" href="../plugins/bootstrap/css/bootstrap.min.css">
    <link rel="stylesheet" href="../plugins/adminLTE/css/AdminLTE.css">
    <link rel="stylesheet" href="../plugins/adminLTE/css/skins/_all-skins.min.css">
    <link rel="stylesheet" href="../css/style.css">


	<script src="../plugins/jQuery/jquery-2.2.3.min.js"></script>
    <script src="../plugins/bootstrap/js/bootstrap.min.js"></script>

    <!-- 富文本编辑器 -->
	<link rel="stylesheet" href="../plugins/kindeditor/themes/default/default.css" />
	<script charset="utf-8" src="../plugins/kindeditor/kindeditor-min.js"></script>
	<script charset="utf-8" src="../plugins/kindeditor/lang/zh_CN.js"></script>
	<!--bootStarpfileinput-->
	<script charset="utf-8" src="../plugins/bootstrap-fileinput/js/fileinput.min.js"></script>
	<link rel="stylesheet" href="../plugins/bootstrap-fileinput/css/fileinput.min.css">


      
    
    
</head>

<body class="hold-transition skin-red sidebar-mini" >

            <!-- 正文区域 -->
            <section class="content">

                <div class="box-body">

                    <!--tab页-->
                    <div class="nav-tabs-custom">

                        <!--tab头-->
                        <ul class="nav nav-tabs">                       		
                            <li class="active">
                                <a href="#home" data-toggle="tab">商品基本信息</a>                                                        
                            </li>   
                            <li >
                                <a href="#pic_upload" data-toggle="tab">商品图片</a>
                            </li>    
                            <li >
                                <a href="#customAttribute" data-toggle="tab">扩展属性</a>                                                        
                            </li>     
                            <li >
                                <a href="#spec" data-toggle="tab" >规格</a>                                                        
                            </li>                       
                        </ul>
                        <!--tab头/-->
						
                        <!--tab内容-->
                        <div class="tab-content">


                            <!--表单内容-->
                            <div class="tab-pane active" id="home">
								<form id="goodsForm">
                                <div class="row data-type">                                  
								   <div class="col-md-2 title">商品分类</div>

		                           	  <div class="col-md-10 data">
		                           	  	<table>
		                           	  		<tr>
		                           	  			<td>
		                           	  				<select class="form-control" id="category1Id" name="category1Id" onchange="change1(this)">
														<option value='-1'>--请选择--</option>
		                           	  				</select>
		                              			</td>
		                              			<td>
		                           	  				<select class="form-control select-sm" id="category2Id" name="category2Id" onchange="change2(this)">
														<option value='-1'>--请选择--</option>
													</select>

		                              			</td>
		                              			<td>
		                           	  				<select class="form-control select-sm" id="category3Id" name="category3Id" onchange="getBrand(this)" >
														<option value='-1'>--请选择--</option>
													</select>
		                              			</td>
		                              			<td >
		                           	  				模板ID:<input id="typeTemplateId" name="typeTemplateId"/>
		                              			</td>
		                           	  		</tr>
		                           	  	</table>
		                              	
		                              </div>	                              
		                          	  
									
		                           <div class="col-md-2 title">商品名称</div>
		                           <div class="col-md-10 data" id="goodsName" >
		                               <input type="text" class="form-control"    placeholder="商品名称" name="goodsName">
		                           </div>
		                           
		                           <div class="col-md-2 title">品牌</div>
		                           <div class="col-md-10 data">
		                              <select class="form-control"  id="brandId" name="brandId">
										  <option>--请选择--</option>
									  </select>
		                           </div>
		
								   <div class="col-md-2 title">副标题</div>
		                           <div class="col-md-10 data" id="caption">
		                               <input type="text" class="form-control"   placeholder="副标题" name="caption">
		                           </div>
		                           
		                           <div class="col-md-2 title">价格</div>
		                           <div class="col-md-10 data">
		                           	   <div class="input-group" id="price">
			                          	   <span class="input-group-addon">¥</span>
			                               <input type="text" class="form-control"  placeholder="价格" name="price">
		                           	   </div>
		                           </div>


		                           <div class="col-md-2 title editer">商品介绍</div>
                                   <div class="col-md-10 data editer">
                                       <textarea name="content" id="introduction"   style="width:800px;height:400px;visibility:hidden;" ></textarea>
                                   </div>
		                           
		                           <div class="col-md-2 title rowHeight2x">包装列表</div>
		                           <div class="col-md-10 data rowHeight2x">
		                               
		                           	<textarea rows="4"  class="form-control"  id="packageList" placeholder="包装列表" name="packageList"></textarea>
		                           </div>
		                           
		                           <div class="col-md-2 title rowHeight2x">售后服务</div>
		                           <div class="col-md-10 data rowHeight2x">
		                               <textarea rows="4"  class="form-control" id="saleService"   placeholder="售后服务" name="saleService"></textarea>
		                           </div>

                                </div>
						</form>
                            </div>



                            <!--图片上传-->
                            <div class="tab-pane" id="pic_upload">
                                <div class="row data-type">                                  
								 <!-- 颜色图片 -->
								 <div class="btn-group">
					                 <input type="button" class="btn btn-default" value="新建" onclick="uploadImg()" data-target="#uploadModal"  data-toggle="modal"  ><i class="fa fa-file-o"></i></input>
                             		                 
					             </div>
								 
								 <table class="table table-bordered table-striped table-hover dataTable">
					                    <thead>
					                        <tr>
					                            
											    <th class="sorting">颜色</th>
											    <th class="sorting">图片</th>
												<th class="sorting">操作</th>
							            </thead>
					                    <tbody id="imageId">

					                    </tbody>
								 </table> 
								  
                                </div>
                            </div>

							<div class="tab-pane" id="customAttribute">
								<div class="row data-type" id="itemCate">

								</div>
							</div>

							<!--规格-->
							<div class="tab-pane" id="spec">
								<div class="row data-type">
									<div class="col-md-2 title">是否启用规格</div>
									<div class="col-md-10 data">
										<input id="checkId"   type="checkbox" onclick="selectSpec()">
									</div>
								</div>
								<div>
									<!--//展示规格选项-->
									<div id="dataType" class="row data-type">

									</div>


									<div  class="row data-type">
										<table class="table table-bordered table-striped table-hover dataTable" id="itemTables"></table>
									</div>

								</div>
							</div>
                            
                        </div>
                        <!--tab内容/-->
						<!--表单内容/-->
							 
                    </div>

                   </div>
                  <div class="btn-toolbar list-toolbar">
				    <!--  <input class="btn btn-primary" onclick="saveGoods()"><i class="fa fa-save" ></i>保存-->
					  <input class="btn btn-primary"  onclick="saveGoods()" value="保存" />
				      <button class="btn btn-default" >返回列表</button>
				  </div>
			
            </section>
            
            
<!-- 上传窗口 -->
<div class="modal fade" id="uploadModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
  <div class="modal-dialog" >
	<div class="modal-content">
		<div class="modal-header">
			<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
			<h3 id="myModalLabel">上传商品图片</h3>
		</div>
		<div class="modal-body">							
			
			<table class="table table-bordered table-striped">
		      	<tr>
		      		<td>颜色</td>
		      		<td><input  class="form-control" placeholder="颜色" id="color" name="color">  </td>
		      	</tr>
		      	<tr>
		      		<td>商品图片</td>
		      		<td>
						<table>
							<tr>
								<td>
								<input type="file" id="myFile" name="myFile" />
								<input type="text" id="image" name="img" />
					            </td>
								<!--<td>
									<img  src="" width="200px" height="200px">
								</td>-->
							</tr>
						</table>
		      		</td>
		      	</tr>		      	
			 </table>				
			
		</div>
		<div class="modal-footer">						
			<input class="btn btn-success"  data-dismiss="modal" aria-hidden="true" value="保存" onclick="saveImag()">
			<button class="btn btn-default" data-dismiss="modal" aria-hidden="true">关闭</button>
		</div>
	  </div>
	</div>

</div>

            
            <!-- 正文区域 /-->
<script type="text/javascript">

	var editor;
	KindEditor.ready(function(K) {
		editor = K.create('textarea[name="content"]', {
			allowFileManager : true
		});
	});

</script>
       
</body>

</html>
<script >
	$(function () {
		getItemCatList(0);
		uploadImg();

	})
	//三级联动
	function getItemCatList(parentId) {
		$.ajax({
			url : "/good/getItemCat",
			dataType:"json",
			type:"post",
			data:{parentId : parentId},
			success:function (result) {
				var category = result.data;
				var html = "<option value='-1'>--请选择--</option>";
				$(category).each(function (i,e){
					html += "<option value='"+e['id']+"'>"+e['name']+"</option>";
				})
				$("#category1Id").html(html);
			},
			error:function (result){
				alert(result.message);
			}
		})
	}
	function change1(obj){
		var parentId = $("#category1Id").val();
		$("#category3Id").html("<option value='-1'>--请选择--</option>");
		$.ajax({
			url:"/good/getItemCat",
			dataType:"json",
			type:"post",
			data:{parentId:parentId},
			async:true,
			success:function (result){
				var category = result.data;
				var html = "<option value='-1'>--请选择--</option>";
				$(category).each(function (i,e){
					html += "<option value='"+e['id']+"'>"+e['name']+"</option>";
				})
				$("#category2Id").html(html);
			},
			error:function (result){
				alert(result.message);
			}
		})
	}
	function change2(obj){
		var parentId = $("#category2Id").val();
		$.ajax({
			url:"/good/getItemCat",
			dataType:"json",
			type:"post",
			data:{parentId:parentId},
			async:true,
			success:function (result){
				var category = result.data;
				var html = "<option value='-1'>--请选择--</option>";
				$(category).each(function (i,e){
					html += "<option value='"+e['id']+"'>"+e['name']+"</option>";
				})
				$("#category3Id").html(html);
			},
			error:function (result){
				alert(result.message);
			}
		})
	}
	var cust12 ;
	//获取模板
	function getBrand(obj){
		var id = $("#category3Id").val();
		$.ajax({
			url:"/good/getBrandByTempId",
			dataType:"json",
			type:"post",
			data:{id:id},
			async:true,
			success:function (result){
				var result = result.data;
				$("#typeTemplateId").val(result.id);
				$("#goodsName").val(result.name);

				var brandIds = result.brandIds;
				let brandIdList = JSON.parse(brandIds);
				//console.log(brandIdList);
				var html = "<option>--请选择--</option>";
				$(brandIdList).each(function (i,e){
					html += "<option value='"+e['id']+"'>"+e['text']+"</option>";
				})
				$("#brandId").html(html);

				// 该商品类型模板拓展属性
				//console.log(result)
				//console.log(result.customAttributeItems)

				cust12= JSON.parse(result.customAttributeItems);
				var custom = "";
				$(cust12).each(function (i, e) {
					custom += "<div>";
					custom += "<div class='col-md-2 title'>" + e.text + "</div>";
					custom += "<div class='col-md-10 data'>";
					custom += "<input class='form-control' name='addCustomAttributeItems11' placeholder='请输入" + e.text + "拓展属性'>";
					custom += "</div>";
					custom += "</div>";
				});
				$("#itemCate").html(custom);
			},
			error:function (result){
				alert(result.message);
			}
		})
	}
	//保存
	function saveGoods() {
		var parentId = $("#category3Id").val();
		alert("保存商品parentId:" + parentId)
		//itemCate 扩展属性    imageId 商品图片
		/*KindEditor.sync();
		let jQuery = $("#introduction").val();
		alert(jQuery)*/

		// 获取扩张属性的名称(全局变量)
		// console.log(cust12);
		// 获取扩展属性的值
		let addCustomAttributeItems = $("[name=addCustomAttributeItems11]");
		let customAttributeItems1 = [];
		for (let i = 0; i < addCustomAttributeItems.length; i++) {
			let cust = {"text": cust12[i].text, "value": addCustomAttributeItems[i].value};
			customAttributeItems1.push(cust);
		}
		// console.log(custItems);
		let customAttributeItems = JSON.stringify(customAttributeItems1);

		// 获取图片信息
		var images = [];
		$("#imageId").find("tr").each(function () {
			let tds = $(this).children();
			let color = tds.eq(0).text().trim();
			let img = tds.eq(1).find("img").attr("src");
			var imgs = {"color": color, "url": img};
			images.push(imgs);
		})
		let itemImages = JSON.stringify(images);
		/*console.log(customAttributeItems);
		console.log(itemImages);*/

		//富文本
		var content = editor.html();
		alert(content)

		//规格页选中规格数据
		var specificationItensJson = JSON.stringify(items);
		console.log(specificationItensJson);

		//拼接tb_item
		var tb_items = [];
		//获取价格 库存
		var trs = $("#specOptionTbody").find("tr");
		console.log(trs)
		//商品名
		var goodsName = $("#goodsName").val();
		for (var j = 0; j < itemList.length; j++) {
			var title = '';
			for (var k = 0; k < items.length; k++) {
				//拼接item中的标题   例:华为 移动3G网络 机身内存16G
				title += goodsName + " " + items[k].attributeName + "" + itemList[j].spec[items[k].attributeName] + " "
			}
			var tds = $(trs[j]).find("td");
			console.log(tds)
			//价格
			var price = $(tds[items.length]).find("input").val()
			//库存
			var num = $(tds[items.length + 1]).find("input").val()
			//是否默认
			var isDefault = $(tds[items.length + 3]).find("input").val()

			//拼接成json字符串
			//       标题           规格                            副标题                   价格          现存            库存         图片                        是否默认
			var item = {
				"title": title,
				"spec": JSON.stringify(itemList[j].spec),
				"sellPoint": $("#caption").val(),
				"price": price,
				"stockCount": num,
				"num": num,
				"image": itemImages[0].url,
				"isDefault": isDefault
			};
			tb_items.push(item)
		}
		var tbItemsJson = JSON.stringify(tb_items)
		var data = $("#goodsForm").serialize() + "&introduction=" + content + "&customAttributeItems=" + customAttributeItems + "&itemImages=" + itemImages + "&str=" + tbItemsJson + "&parentId=" + parentId+ "&specificationItems=" + specificationItensJson;
		console.log(data);
		$.ajax({
			url: "/good/saveGoods",
			dataType: "json",
			type: "post",
			data: data,
			async: true,
			success: function (result) {
				alert(result.message);
				window.top.location.href = "toIndex";
			},
			error: function (result) {
				alert(result.message);
			}
		})
	}//上传图片
	function uploadImg() {
		$('#myFile').fileinput({
			language: 'zh',
			uploadUrl: "/oss/upload",
			enctype:'multipart/form-data',
			browseClass: 'btn btn-primary',

			allowedFileExtensions:["jpg","gif","png"],
			maxFileSize:1024,//kb
			maxFileCount:5
		});
		$('#myFile').on('fileuploaded',function (event,data,previewId,index){
			if (data.response != null){
				$("#image").val(data.response.data)
				/*$("[name=rimage]").val(data.response.imgUrl);*/
			}
		})
	}


	//增加商品图片
	function saveImag() {
		var color = $("#color").val();
		var imageUrl = $("#image").val();
		// 拼接在页面上
		var goodsImages = '  <tr>\t\t\t\t\t                           \n' +
				'\t\t\t\t\t\t\t\t\t            <td>\n' +color+
				'\t\t\t\t\t\t\t\t\t            \t\n' +
				'\t\t\t\t\t\t\t\t\t            </td>\n' +
				'\t\t\t\t\t\t\t\t\t            <td>\n' +
				'\t\t\t\t\t\t\t\t\t           \t\t<img alt="" src="'+imageUrl+'" width="100px" height="100px">\t            \t \n' +
				'\t\t\t\t\t\t\t\t\t            </td>\n' +
				'\t\t\t\t\t\t\t\t\t\t\t\t <td> <button type="button" class="btn btn-default" title="删除" onclick="deleteGoodsImage(this)"><i class="fa fa-trash-o"></i> 删除</button></td> \n' +
				'\t\t\t\t\t                      </tr>';
		$("#imageId").append(goodsImages);

		// 清空图片弹出窗口
		$("#uploadModal input").val("");
	}

	// 删除图片编辑中的tr
	function deleteGoodsImage(o) {
		// 获取button的tr
		var tr = o.parentNode.parentNode;
		// 获取这个tr的tbody
		var tbody = tr.parentNode;
		// 删除这个button所在的tr
		tbody.removeChild(tr);
	}

	//启用规格 展示规格数据
	function selectSpec(){

		var parentId =$("#category3Id").val();
		alert(parentId)
		if (parentId == -1){
			alert("前选择商品分类")
			return;
		}else {
			$.ajax({
				url:"/good/getSpecOptions",
				type:"post",
				dataType:"json",
				data:{id:parentId},
				success:function (result){
					var speOp = result.data;
					var html = '';
					if ($("#checkId").is(":checked")) {
						$.each(speOp,function (i,e) {
							html +='<div><div class="col-md-2 title">'+e.text+'</div>'
							html +='<div class="col-md-10 data">';
							$.each(e.options,function (index,ele) {
								html +='<span>'
								html +='<input  onclick="checkSpec(this,\''+e.text+'\',\''+ele.optionName+'\')" ' +
										'type="checkbox" value="'+ele.id+'" >'+ele.optionName+'</span>'

							})
							html +='</div></div>'

						});
						$("#dataType").html(html)

					}

				},
				error:function (){
					alert("失败")
				}
			})
		}
	}
	//勾选规格选项复选框函数
	function checkSpec(event,name,value){
		//调用方法判断原集合中是否已有attributeName
		var obj = searchObjectByKey(items,'attributeName',name);
		if(obj != null){
			if($(event).prop('checked')){//勾选
				//如果之前有数据，往原有的对象中追加
				obj.attributeValue.push(value);
			}else{//取消勾选
				obj.attributeValue.splice(obj.attributeValue.indexOf(value),1)//从items中移除规格选项
				//如果规格选项没有数据了
				if(obj.attributeValue.length==0){
					//移除items中的数据
					items.splice(items.indexOf(obj),1)
				}
			}
		}else{
			//如果之前没有数据，items新加数据
			items.push({'attributeName':name,'attributeValue':[value]});
		}
		//console.log(items);
		//后续调用，这里先不调用，后续选择之后组装选择后的数据用的
		createItemList();
	}

	//遍历组装用户勾选规格选项数据
	function searchObjectByKey(list,attributeName,attributeValue){
		for(var i=0;i<list.length;i++){
			//如果list中我们选择key存在
			if(list[i][attributeName] == attributeValue){
				return list[i];//返回当前对象
			}
		}
		//遍历结束后都不存在，返回null
		return null;
	}
	//创建SKU列表
	function createItemList(){
		//创建初始值
		var itemList = [{spec:{}}] ;
		for(var i = 0; i < items.length; i++){
			itemList =  addColum(itemList,items[i].attributeName,items[i].attributeValue);
		}
		console.log(itemList);
	}

	//添加表格的列
	function addColum(list,columName,columValues) {
		//定义新集合接收行
		var newList = [];
		for(var i = 0; i < list.length; i++){
			var oldRow = list[i];
			for(var j=0; j < columValues.length; j++){
				var newRow = JSON.parse(JSON.stringify(oldRow)); //深克隆
				newRow.spec[columName] = columValues[j];
				newList.push(newRow)
			}
		}
		return newList;
	}
	var items = [];
	//勾选规格选项复选框函数
	function checkSpec(event,name,value){
		//调用方法判断原集合中是否已有attributeName
		var obj = searchObjectByKey(items,'attributeName',name);
		if(obj != null){
			if($(event).prop('checked')){//勾选
				//如果之前有数据，往原有的对象中追加
				obj.attributeValue.push(value);
			}else{//取消勾选
				obj.attributeValue.splice(obj.attributeValue.indexOf(value),1);//从items中移除规格选项
				//如果规格选项没有数据了
				if(obj.attributeValue.length==0){
					//移除items中的数据
					items.splice(items.indexOf(obj),1)
				}
			}
		}else{
			//如果之前没有数据，items新加数据
			items.push({'attributeName':name,'attributeValue':[value]});
		}
		// 构建勾选的规格数据
		createItemList(event);
	}

	//遍历组装用户勾选规格选项数据
	function searchObjectByKey(list,attributeName,attributeValue){
		for(var i=0;i<list.length;i++){
			//如果list中我们选择key存在
			if(list[i][attributeName] == attributeValue){
				return list[i];//返回当前对象
			}
		}
		//遍历结束后都不存在，返回null
		return null;
	}

	//创建SKU列表
	var itemList = null;
	function createItemList(event){
		var itemList2 = [{spec:{}}] ;
		for(var i = 0; i < items.length; i++){
			itemList2 =  addColum(itemList2,items[i].attributeName,items[i].attributeValue);
		}
		itemList = itemList2;

		// 构建table
		var table = "";
		table += '<thead>'
		table += '<tr>'
		for (var f = 0; f < items.length; f++) {
			table += '<th class="sorting">' + items[f].attributeName + '</th>'
		}

		table += '<th class="sorting">价格</th>'
		table += '<th class="sorting">库存</th>'
		table += '<th class="sorting">是否启用</th>'
		table += '<th class="sorting">是否默认</th>'
		table += '</tr>'
		table += '</thead>'
		table += '<tbody id="specOptionTbody">'
		for (var j = 0; j < itemList.length; j++) {
			table += '<tr>'
			for (var e = 0; e < items.length; e++) {
				table += '<td>' + itemList[j].spec[items[e].attributeName] + '</td>'
			}
			table += '<td>'
			table += '<input class="form-control"  placeholder="价格"></td>'
			table += '<td><input class="form-control" placeholder="库存数量"></td>'
			table += '<td><input type="checkbox" ></td>'
			table += '<td> <input type="checkbox" value="1"></td>'
			table += '</tr>'
		}
		table += '</tbody>'
		$("#itemTables").html(table)
	}

	//添加表格的列
	function addColum(list,columName,columValues) {
		//定义新集合接收行
		var newList = [];
		for(var i = 0; i < list.length; i++){
			var oldRow = list[i];
			for(var j=0; j < columValues.length; j++){
				var newRow = JSON.parse(JSON.stringify(oldRow)); //深克隆
				newRow.spec[columName] = columValues[j];
				newList.push(newRow)
			}
		}
		return newList;
	}
</script>
